#!/bin/bash

if [ ! $# -eq 2 ]
then
    echo "You need to provide both project name and virtualhost name as arguments !"
	exit
fi

cd /usr/local
if [ ! -e /usr/local/django ] 
then
	mkdir django
else
	echo "/usr/local/django already exists"
fi
cd django

if [ -e /usr/local/django/$1 ]
then
	echo "Project $1 already exists in /usr/local/django/ !"
	exit 0
else
	django-admin.py startproject $1
	cd $1
	mkdir templates apache media static
	sed -i '1 a import os' settings.py
	sed -i '2 a ROOT_PATH = os.path.dirname(__file__)' settings.py
	sed -i 's/django\.db\.backends\./&sqlite3/' settings.py
	sed -i "/DATABASES/,/}/ s/\('NAME': \)\(''\)/\1os\.path\.join(ROOT_PATH\,'sqlite\.db')/" settings.py
	sed -i "s/\(TIME_ZONE = '\)\(.*\)\('\)/\1Europe\/Brussels\3/" settings.py
	sed -i "s/\(LANGUAGE_CODE = '\)\(.*\)\('\)/\1fr-fr\3/" settings.py
	sed -i "s/\(MEDIA_ROOT = \)\(.*\)$/\1os\.path\.join(ROOT_PATH\,'media\/')/" settings.py
	sed -i "s/\(MEDIA_URL = \)\(.*\)$/\1'\/media\/'/" settings.py
	sed -i "s/\(STATIC_ROOT = \)\(.*\)$/\1os\.path\.join(ROOT_PATH\,'static\/')/" settings.py
	sed -i "/TEMPLATE_DIRS/,/INSTALLED_APPS/ s#^)#    os.path.join(ROOT_PATH,'templates'),\n&#" settings.py
	sed -i "/INSTALLED_APPS/,/^)/ s/# *\('django\)/\1/" settings.py
	sed -i "/# Uncomment the next two lines/{N;N;s/# //2g}" urls.py
	sed -i "/^urlpatterns/,/^)/ s/\([ \t]*\)# *\(url(r'^admin.*\)$/\1\2/" urls.py

	python2.7 manage.py syncdb

	chgrp apache sqlite.db .
	chmod g+w sqlite.db .

	echo "import os, sys
sys.path.append('/usr/local/django')
sys.path.append('/usr/local/django/$1')
os.environ['DJANGO_SETTINGS_MODULE'] = '$1.settings'

import django.core.handlers.wsgi

application = django.core.handlers.wsgi.WSGIHandler()" > apache/django.wsgi

	echo "<VirtualHost *:80>
    ServerAdmin webmaster@$2
    ServerName $2
    ErrorLog logs/$2-error
    CustomLog logs/$2-access common

    Alias /static/ /usr/local/django/$1/static/

    <Directory /usr/local/django/$1/static>
        Order deny,allow
        Allow from all
    </Directory>
    
    Alias /media/ /usr/local/django/$1/media/

    <Directory /usr/local/django/$1/media>
        Order deny,allow
        Allow from all
    </Directory>

    WSGIScriptAlias / /usr/local/django/$1/apache/django.wsgi

    <Directory /usr/local/django/$1/apache>
        Order deny,allow
        Allow from all
    </Directory>
</VirtualHost>" >> /etc/httpd/conf/httpd.conf
    ln -s /usr/local/lib/python2.7/site-packages/django/contrib/admin/media static/admin
    # active les hôtes virtuels nommés ( pas ici -> lors de la création des virtualhost dans start_django_project
    sed -i "s/^#.*\(NameVirtualHost\).*\(\*\:80$\)/\1 \2/" /etc/httpd/conf/httpd.conf
    service httpd restart
fi

